package com.tb.ClassSchedule;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.HashSet;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Toolbar.OnMenuItemClickListener{

    private Toolbar toolbar;
    //方便获取context
    public static MainActivity      main;
    // 状态栏高度
    public static int               statusBarHeight;
    //数据存储
    public static SharedPreferences sharedPreferences;
    //显示周数的按钮
    private       Button            weekListButton;
    //侧侧边栏
    public       DrawerLayout      drawerLayout;
    //总布局
    private       LinearLayout      bgLayout;
    //记录当前周和选择周
    public        int               selectedWeek;
    public        int               currentWeek;
    //所以课程信息数组
    private       HashSet<Lesson>           lessonsInfos;


    public static int DEFAULT_THEME;
    public static int mainViewMode;
    public static final int DAY_MODE = 0;
    public static final int WEEK_MODE = 1;

    private     MainDayView  mainViewDay;
    private MainWeekView mainViewWeek;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //主视图布局
        setContentView(R.layout.activity_main);
        //赋值context
        main = this;

        //获取状态栏高度
        statusBarHeight = getStatusBarHeight();
        Log.d("Tb","statusBarHeight :" + statusBarHeight);
        //初始化存储
        sharedPreferences = getSharedPreferences("data", Context.MODE_PRIVATE);
        //获取当前周
        currentWeek = TimeManager.getCurrentWeek();
        selectedWeek = currentWeek;
        //侧边栏
//        drawerLayout = SideMenu.getInstance();
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        //初始化背景
        bgLayout = (LinearLayout) findViewById(R.id.bg);
        //toolbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        //周列表按钮
        weekListButton = (Button) findViewById(R.id.week_list_button);
        //初始化toolbar
        initToolBar();
        DEFAULT_THEME = ContextCompat.getColor(this, R.color.defaultColor1);
        setBgColor(sharedPreferences.getInt("color",MainActivity.DEFAULT_THEME));

        mainViewWeek = (MainWeekView) findViewById(R.id.main_view_week);
        mainViewDay = (MainDayView) findViewById(R.id.main_view_day);

        draw();



    }

    private void initToolBar(){
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            toolbar.setPadding(0,MainActivity.statusBarHeight,0,0);
        }
        toolbar.setOnMenuItemClickListener(this);

        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        mDrawerToggle.syncState();
        drawerLayout.addDrawerListener(mDrawerToggle);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return true;
    }

    public void setBgColor(int color) {
        bgLayout.setBackgroundColor(color);
//        toolbar.setBackgroundColor(color);

    }

    public void draw(){

        //绘制周指示器
        String buttonStr = "";
        switch (selectedWeek){
            case 0:
                buttonStr = "未开学";
                break;
            case 21:
                buttonStr = "结束啦";
                break;
            default:
                buttonStr = "第" + selectedWeek + "周";

        }
        if( selectedWeek != currentWeek){
            buttonStr += "(非本周)";
            weekListButton.setTextColor(Color.BLACK);
            weekListButton.setTextSize(15);
        }else{
            weekListButton.setTextColor(Color.WHITE);
            weekListButton.setTextSize(20);
        }
        weekListButton.setText(buttonStr);


        //获取课表信息数据
        lessonsInfos = new LessonSet();

        //绘制课表
        mainViewMode = sharedPreferences.getInt("mainViewMode",WEEK_MODE);
        switch (mainViewMode){
            case WEEK_MODE:
                mainViewWeek.setVisibility(View.VISIBLE);
                mainViewDay.setVisibility(View.GONE);
                mainViewWeek.drawClasses(lessonsInfos,selectedWeek);
                break;
            case DAY_MODE:
                mainViewDay.setVisibility(View.VISIBLE);
                mainViewWeek.setVisibility(View.GONE);
                mainViewDay.drawClasses(lessonsInfos,selectedWeek);
                break;
            default:
                mainViewWeek.setVisibility(View.GONE);
                mainViewDay.setVisibility(View.GONE);
        }


    }



    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                doubleBackForExit();
                break;
            default:
                super.onKeyUp(keyCode,event);
        }

        return true;
    }


    private boolean isExit;
    private void doubleBackForExit(){
        if(isExit){
            finish();
            System.exit(0);
        }else {
            Toast.makeText(this,"再按一次退出",Toast.LENGTH_SHORT).show();
            isExit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isExit = false;
                }
            },2000);
        }
    }


    @Override
    public void onClick(View view) {

    }

    private int getStatusBarHeight(){
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0,sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = getResources().getDimensionPixelOffset(x);

        }catch (Exception e){
            e.printStackTrace();
        }

        return sbar;

    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        Intent intent = new Intent();
        switch (item.getItemId()){
            case R.id.add_class_button:
                intent.setClass(main,AddClassActivity.class);
                main.startActivity(intent);
                break;
            case R.id.set_week_button:
                TimeManager.setCurrentWeekDialog();
                break;
            case R.id.table_bg_button:
                intent.setClass(main,SetThemeActivity.class);
                main.startActivity(intent);
                break;
            case R.id.chang_view_button:
                MainActivity.mainViewMode = (MainActivity.mainViewMode + 1) % 2;
                SharedPreferences.Editor editor = MainActivity.sharedPreferences.edit();
                editor.putInt("mainViewMode",MainActivity.mainViewMode);
                editor.commit();
                editor.clear();
                draw();
                break;
        }
        return true;
    }
}
